<template>
  <div>
    <el-card>
      <template #header>
        <el-form :model="conditionForm" inline>
          <el-form-item label="企业名称" style="width: 230px;">
            <el-select
              v-model="conditionForm.enterpriseCode"
              filterable
              clearable
              placeholder="请选择公司名称"
              @change="query()"
            >
              <el-option
                v-for="item in options"
                :key="item.enterpriseId"
                :label="item.cmpName"
                :value="item.enterpriseCode"
              />
              <template #prefix>
                <el-icon class="el-input__icon"><search /></el-icon>
              </template>
            </el-select>
          </el-form-item>
          <el-form-item label="是否需要上报" style="width: 250px;">
            <el-select
              v-model="conditionForm.escalation"
              filterable
              clearable
              placeholder="请选择"
              @change="query()"
            >
              <el-option
                v-for="item in escalationOption"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
              <template #prefix>
                <el-icon class="el-input__icon"><search /></el-icon>
              </template>
            </el-select>
          </el-form-item>
          <el-button @click="open()" type="primary"
            >新增<el-icon style="margin-left: 5px"><Plus /></el-icon>
          </el-button>
        </el-form>
      </template>
      <el-table
        :data="tableData"
        style="width: 100%; max-height: 61vh; height: 61vh"
        table-layout="fixed"
        v-loading="loading"
        :header-cell-style="{'text-align':'center'}"
        :cell-style="{'text-align':'center'}"
      >
        <el-table-column fixed min-width="70" prop="enterName" label="企业名称" />
        <el-table-column prop="enterpriseCode" label="社会信用代码" />
        <el-table-column prop="flag" label="属性标识" />
        <!-- <el-table-column prop="escalation" label="是否需要上报" /> -->
        <el-table-column prop="escalation" label="是否需要上报" filter-placement="bottom-end" >
          <template #default="scope">
            <el-tag
              :type="scope.row.escalation === '1' ? 'warning' : 'success'"
              disable-transitions
              >{{ label[Number(scope.row.escalation)].label }}</el-tag
            >
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作">
          <template #default="scope">
            <el-button
              link
              type="primary"
              @click="
                editOpen(scope.$index, scope.row);
                dialogTableVisible = true;
              "
              >编辑</el-button
            >
            <el-popover
              placement="top-start"
              title="删除操作"
              :width="200"
              trigger="click"
              :visible="visibleSS[scope.$index]"
            >
              <p>确定要进行删除吗?</p>
              <div style="text-align: right; margin: 0">
                <el-button
                  size="small"
                  text
                  @click="visibleSS[scope.$index] = false"
                  >取消</el-button
                >
                <el-button
                  size="small"
                  type="primary"
                  @click="deleteById(scope.$index, scope.row)"
                  >确定</el-button
                >
              </div>
              <template #reference>
                <el-button
                  link
                  type="danger"
                  ref="buttonRefs"
                  @click="visibleSS[scope.$index] = true"
                  >删除</el-button
                >
              </template>
            </el-popover>
          </template>
        </el-table-column>
      </el-table>
      <div class="card-footer">
        <el-pagination
          layout="total, sizes, prev, pager, next, jumper"
          :page-sizes="[10,20,30,40,50,100,500]"
          background
          v-model:page-size="pagination.size"
          v-model:current-page="pagination.page"
          :total="pagination.total"
          @size-change="sizeChange"
          @current-change="pageChange"
          class="pagination"
        />
      </div>
    </el-card>
    <el-dialog v-model="dialogTableVisible" width="500" :title="dialogTitel">
      <el-form
        label-position="right"
        label-width="150px"
        :model="formData"
        style="margin-right: 20px"
        ref="ruleFormRef"
        :rules="rule"
      >
        <el-form-item label="企业名称" prop="enterpriseCode">
          <el-select
            v-model="formData.enterpriseCode"
            filterable
            clearable
            placeholder="请选择公司名称"
            :disabled="enterDisable"
            @change="doProjectData"
          >
            <el-option
              v-for="item in options"
              :key="item.enterpriseId"
              :label="item.cmpName"
              :value="item.enterpriseCode"
            />
            <template #prefix>
              <el-icon class="el-input__icon"><search /></el-icon>
            </template>
          </el-select>
        </el-form-item>
        <el-form-item label="社会信用代码" prop="enterpriseCode">
          <el-input v-model="formData.enterpriseCode" disabled />
        </el-form-item>
        <el-form-item label="是否需要上报" prop="escalation">
          <el-select
            v-model="formData.escalation"
            filterable
            clearable
            placeholder="请选择"
          >
            <el-option
              v-for="item in escalationOption"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
            <template #prefix>
              <el-icon class="el-input__icon"><search /></el-icon>
            </template>
          </el-select>
        </el-form-item>
        <el-form-item label="属性标识" prop="flag">
          <!-- <el-input v-model="formData.flag" /> -->
          <el-select
            v-model="formData.flag"
            filterable
            clearable
            multiple
            collapse-tags
            placeholder="请选择"
          >
            <el-option
              v-for="item in flagOption"
              :key="item.projectId"
              :label="item.paramName"
              :value="item.flag"
            >
              <span style="float: left">{{ item.paramName }}</span>
              <span
                style="
                  float: right;
                  color: var(--el-text-color-secondary);
                  font-size: 13px;
                "
                >{{ item.flag }}</span
              >
            </el-option>
            <template #prefix>
              <el-icon class="el-input__icon"><search /></el-icon>
            </template>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button @click="dialogTableVisible = false" type="info"
            >取消</el-button
          >
          <el-button type="primary" @click="submitForm(ruleFormRef)">
            确定
          </el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup>
import { reactive, ref } from "vue";
import { getNameList } from "@/api/enterprise";
import {
  pageList,
  saveOrUpdate,
  getList,
  save,
  updateById,
  removeById,
} from "@/api/admin/devicePoint/index";
import { deleteEmptyProperty, fn2 } from "@/utils/index.js";
import { ElMessage } from "element-plus";
const pagination = reactive({
  page: 1,
  size: 10,
  total: 0,
});
const options = ref([]);
const enterDisable = ref(false);
const tableData = ref([]);
const flagOption = ref([]);
let formData = reactive({
  projectId: "",
  enterpriseCode: "",
  enterpriseName: "",
  projectId: "",
  flag: [],
  escalation: "",
});
const escalationOption = ref([
  { value: "1", label: "需要" },
  { value: "0", label: "不需要" },
]);
let label = [
  {
    label: "否",
  },
  {
    label: "是",
  },
];
const conditionForm = reactive({
  enterpriseCode: "",
  escalation: "",
});
const condition = ref([]);
const loading = ref(false);
const visibleSS = ref([]);
const ruleFormRef = ref();
const dialogTitel = ref("");
const isEdit = ref(false);
let rule = {};
const dialogTableVisible = ref(false);
const sizeChange = (value) => {
  pagination.size = value;
  pagination.page = 1;
  doDataList();
};
/**
 * 页总数改变
 */
const pageChange = (value) => {
  pagination.page = value;
  doDataList();
};

const doDataList = () => {
  loading.value = true;
  getNameList()
    .then((res) => {
      options.value = res.data;
      let datas = {
        pageNum: pagination.page,
        pageSize: pagination.size,
        condition: JSON.stringify(condition.value),
      };
      pageList(datas)
        .then((res) => {
          if (res.status == 200) {
            tableData.value = res.data.records;
            pagination.size = res.data.pageSize;
            pagination.page = res.data.currentPage;
            pagination.total = res.data.total;
            doEnterName();
            loading.value = false;
          }
        })
        .catch((msg) => {});
    })
    .catch((msg) => {});
};
const doEnterName = () => {
  let tempTableData = tableData.value;
  let tempOptions = options.value;
  for (let i = 0; i < tempTableData.length; i++) {
    for (let j = 0; j < tempOptions.length; j++) {
      if (tempTableData[i].enterpriseCode === tempOptions[j].enterpriseCode) {
        tempTableData[i].enterName = tempOptions[j].cmpName;
      }
    }
  }
  tableData.value = tempTableData;
};
//查询
const query = () => {
  let c = deleteEmptyProperty(conditionForm);
  let temp = {};
  let conditions = [];
  condition.value = [];
  for (let cloumn in c) {
    switch (cloumn) {
      case "enterpriseCode":
        temp = {
          column: "enterpriseCode",
          type: "like",
          value: c[cloumn],
        };
        break;

      case "escalation":
        temp = {
          column: "escalation",
          type: "eq",
          value: c[cloumn],
        };
        break;
    }
    conditions.push(temp);
  }
  condition.value = conditions;
  doDataList();
};
const editOpen = (index, rowData) => {
  let data = rowData;
  data.flag = rowData.flag.split(",");
  formData = reactive(data);
  doProjectData();
  enterDisable.value = true;
  isEdit.value = true;
  dialogTitel.value = "编辑";
  dorule();
};
const dorule = () => {
  for (let key in formData) {
    let tempd = JSON.parse(
      '[{"required":true,"message":"请输入数据","trigger":"blur"}]'
    );
    rule[key] = tempd;
  }
};
const submitForm = async (formEl) => {
  await formEl.validate((valid, fields) => {
    if (valid) {
      //验证成功,开始进行数据的更新或者新增
      let data = formData;
      data.flag = formData.flag.join(",");
      if (isEdit.value == true) {
        updateById(data)
          .then((res) => {
            if (res.status == 200) {
              ElMessage.success(res.message);
              doDataList();
              dialogTableVisible.value = false;
            }
          })
          .catch((msg) => {});
          return;
      }
      save(data)
        .then((res) => {
          if (res.status != 200) {
            ElMessage.error("上传数据失败,请联系管理员!");
            return;
          }
          ElMessage.success("上传成功！");
          doDataList();
          dialogTableVisible.value = false;
        })
        .catch((msg) => {});
    } else {
      console.log("error submit!", fields);
    }
  });
};
/**
 * 更改数据
 */
const doProjectData = (data) => {
  for (let i = 0; i < options.value.length; i++) {
    if (data == options.value[i].enterpriseCode) {
      formData.projectId = options.value[i].enterpriseId;
      break;
    }
  }
  getList({ projectId: formData.projectId })
    .then((res) => {
      flagOption.value = fn2(res.data);
    })
    .catch((msg) => {});
};
//新增
const open = () => {
  formData = reactive({
    enterpriseCode: "",
    flag: "",
    escalation: "",
  });
  enterDisable.value = false;
  dialogTitel.value = "新增";
  dialogTableVisible.value = true;
  isEdit.value = false;
  dorule();
};
//删除
const deleteById = (index, rowData) => {
  removeById({ projectId: rowData.projectId })
    .then((res) => {
      if (res.status == 200) {
        ElMessage.success(res.message);
        visibleSS.value[index] = false;
        doDataList();
      }
    })
    .catch((msg) => {});
};
doDataList();
</script>

<style lang="less" scoped>
.title {
  min-width: 5em;
}
.el-table .warning-row {
  --el-table-tr-bg-color: var(--el-color-warning-light-9);
}
.el-table .success-row {
  --el-table-tr-bg-color: var(--el-color-success-light-9);
}
.el-card__header {
  max-height: 10vh;
}
.pagination {
  max-height: 3vh;
}
.demo-form-inline .el-input {
  --el-input-width: 300px;
}
.el-form-item__label {
  line-height: 25px;
}
.el-form-item {
  margin-bottom: 0px;
}
.card-footer {
  display: flex;
  justify-content: flex-end;
  align-items: flex-end;
}
.total-font {
  margin-right: 15px;
  font-weight: 500;
  line-height: 21px;
  color: #595959;
}
</style>
